 //
//  JLJTools.m
//  BZW
//
//  Created by Kaka on 16/6/16.
//  Copyright © 2016年 Kaka. All rights reserved.
//

#import "JLJTools.h"
//#import <MBProgressHUD.h>
//#import <SVProgressHUD.h>
#import "CKAlertViewController.h"
//#import "JPUSHService.h"



//extern NSString *CTSettingCopyMyPhoneNumber();

@interface JLJTools()


@property (nonatomic,assign) InternetStatus *internetStatus;
@property (nonatomic,assign) int socket;
@property (nonatomic,strong) NSTimer *timer;

@end
@implementation JLJTools

+ (instancetype)shareInstance
{
    static JLJTools *instance = nil;
    static dispatch_once_t onceTocken;
    
    dispatch_once(&onceTocken, ^{
        instance = [[JLJTools alloc] init];
    });
    
    return instance;
}
- (void)setView:(UIView *)view BoaderWithWidth:(CGFloat)width radius:(CGFloat)radius coloc:(UIColor *)color andToBounds:(BOOL)yesOrNO
{
    [[view layer] setBorderWidth:width];//画线的宽度
    [[view layer] setBorderColor:color.CGColor];//颜色
    [[view layer]setCornerRadius:radius];//圆角
    [view.layer setMasksToBounds:yesOrNO];
}


////MBProgress文字提示
//- (void) showMBHudWithString:(NSString *) massage andShowView:(UIView *) view{
//
//    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
//    hud.mode = MBProgressHUDModeText;
//    hud.labelText = massage;
//    hud.margin = 10.f;
//    hud.yOffset = 150.f;
//    hud.removeFromSuperViewOnHide = YES;
//    [hud hide:YES afterDelay:2];
//}

////正在进行中
//- (void)ShowWithString:(NSString *)message
//{
//    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
//    [SVProgressHUD showWithStatus:message];
//    [SVProgressHUD setMinimumDismissTimeInterval:0.5];
//}
////
- (void)ShowInfoWithString:(NSString *)message withTime:(NSTimeInterval)time
{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showInfoWithStatus:message];
    [SVProgressHUD setMinimumDismissTimeInterval:time];
}
////正在进行中
//- (void)AliOSSShowWithString:(NSString *)message
//{
//    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
//    [SVProgressHUD showWithStatus:message];
//    [SVProgressHUD setMinimumDismissTimeInterval:1.5];
//}
//
////返回SVProgressSuccess
- (void)ShowSuccessWithString:(NSString *)message withTime:(NSTimeInterval)time
{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showSuccessWithStatus:message];
    [SVProgressHUD setMinimumDismissTimeInterval:time];
}

////返回SVProgressError
- (void)ShowErrorWithString:(NSString *)message withTime:(NSTimeInterval)time
{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showErrorWithStatus:message];
    [SVProgressHUD setMinimumDismissTimeInterval:time];
}
////消失SVProgressHUD
//- (void)dismissSVProgressHUD {
//    [SVProgressHUD dismiss];
//    [SVProgressHUD setMinimumDismissTimeInterval:1.5];
//
//}
#pragma mark 处理图片
-(NSData *)handleImage:(UIImage *) item{
    NSData * data;
    //处理图片
    UIImage * newImage;
    if(item.size.height>1000||item.size.width>1000){
        newImage = [self scaleFromImage:item toSize:CGSizeMake(500, 500)];
    }else {
        newImage = item;
    }

    if (UIImagePNGRepresentation(newImage) == nil) {
        //返回为png图像。
        data = UIImageJPEGRepresentation(newImage, 1.0);
//        data = UIImagePNGRepresentation(newImage);
    }else {
        //返回为JPEG图像。
//        data = UIImageJPEGRepresentation(newImage, 0.8);
        data = UIImagePNGRepresentation(newImage);
    }
    return data;
}
//等比缩放
//通过缩放系数
#pragma  mark 缩放图片
- (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size {
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
#pragma mark - 得到登陆地区等级
- (NSInteger) getUserLevel{
    
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    
    NSString * mark =[ud objectForKey:@"JLJMark"];
    
    NSInteger level = [mark integerValue];
    
    return level;
}

//获取几天后的时间
- (NSDate *)dateWithInt:(NSInteger)dayCount
{
    NSDate *date = [[NSDate alloc] init];
    
    return [date dateByAddingTimeInterval:-dayCount * 3600 * 24];
}
//获取当前时间
- (NSString *)dateWithDate:(NSDate *)date
{
    NSDateFormatter *formater = [[NSDateFormatter alloc]init];
    
    [formater setDateFormat:@"yyyy-M-d HH:mm:ss"];
    
    return  [formater stringFromDate:date];
}
//获取当前的月和日
- (NSString *)monthAddDay:(NSDate *)date
{
    NSDateFormatter *formater = [[NSDateFormatter alloc]init];
    
    [formater setDateFormat:@"MM-dd"];
    
    return  [formater stringFromDate:date];
}

#pragma mark - 判断时间
- (int)compareDate:(NSString*)date01 withDate:(NSString*)date02{
    int ci;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
    dt1 = [df dateFromString:date01];
    dt2 = [df dateFromString:date02];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result)
    {
            //date02比date01大
        case NSOrderedAscending: ci=1; break;
            //date02比date01小
        case NSOrderedDescending: ci=-1; break;
            //date02=date01
        case NSOrderedSame: ci=0; break;
        default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
    }
    return ci;
}

#pragma mark  把时间转化为时间戳
-(NSInteger)getTimestamp:(NSString *)time{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [formatter dateFromString:time];
    
    NSInteger interval = [date timeIntervalSince1970];
    
    
    return interval;
    
}
#pragma mark  把时间戳转为时间
-(NSString *)getTimeString:(NSString *)timeStamp setDateFormat:(NSString *)dateFormat {
    NSString *str = timeStamp;//时间戳
    
    NSTimeInterval time=[str doubleValue];//因为时差问题要加8小时 == 28800 sec
    
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:dateFormat];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    
    return currentDateStr;
    
}
- (NSString *)updateTimeForRow:(NSString * )timeStamp {
    // 获取当前时时间戳 1466386762.345715 十位整数 6位小数
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    
    // 时间差
    NSTimeInterval time = currentTime - [timeStamp integerValue];
    // 秒转分钟
    NSInteger mint = time/60;
    if (mint<60) {
        if (mint < 1) {
            return @"刚刚";
        }
        return [NSString stringWithFormat:@"%ld分钟前",(long)mint];
    }
    
    // 秒转小时
    NSInteger hours = time/3600;
    if (hours<24) {
        return [NSString stringWithFormat:@"%ld小时前",(long)hours];
    }
    //秒转天数
    NSInteger days = time/3600/24;
//    if (days < 30) {
        if (days==1) {
            return @"昨天";
        }else if (days<7){
        
        return [NSString stringWithFormat:@"%ld天前",(long)days];
        
        }
    
    return [self getTimeString:timeStamp setDateFormat:@"yyyy-MM-dd"];
    
        
        
//    }
    //秒转月
//    NSInteger months = time/3600/24/30;
//    if (months < 12) {
//        return [NSString stringWithFormat:@"%ld月前",(long)months];
//    }
//    //秒转年
//    NSInteger years = time/3600/24/30/12;
//    return [NSString stringWithFormat:@"%ld年前",(long)years];
}
/**
 *  根据日期获取周几
 *
 *  @param inputDate 计算的日期
 *
 *  @return 周几
 */
- (NSString *)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Beijing"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}
/**
 *  创建消息
 *
 *  @param name   消息唯一名
 *  @param object 传递的数据
 */
- (void)postNSNotifiCtionCenterWithName:(NSString *)name object:(id)object{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:name object:object];
}
/**
 *  接收消息
 *
 *  @param observer 接受者
 *  @param sel      接收时间
 *  @param name     接收消息名
 *  @param object   传递参数
 */
- (void)addObserverNsNotificationObservr:(id)observer sel:(SEL)sel name:(NSString *)name object:(id)object{
    
    [[NSNotificationCenter defaultCenter] addObserver:observer selector:sel name:name object:object];
}
/**
 *  移除消息
 *
 *  @param observer 移除消息者
 */
- (void)cancelNSNotificationWithObserve:(id)observer{
    
    [[NSNotificationCenter defaultCenter] removeObserver:observer];
}

//正则表达
//邮箱判断
- (BOOL)isEmailAddress:(NSString*)candidate
{
    NSString* emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate* emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:candidate];
}
//手机号验证

/**
 *  手机号码验证
 *
 *  @param mobileNumbel 传入的手机号码
 *
 *  @return 格式正确返回true  错误 返回fals
 */
- (BOOL) isMobile:(NSString *)mobileNumbel{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,181(增加)
     */
    NSString * MOBIL = @"^1(3[0-9]|5[0-35-9]|8[0245-89]|7[0])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189,181(增加)
     22         */
    NSString * CT = @"^1((33|53|8[019|77])[0-9]|349)\\d{7}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBIL];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNumbel]
         || [regextestcm evaluateWithObject:mobileNumbel]
         || [regextestct evaluateWithObject:mobileNumbel]
         || [regextestcu evaluateWithObject:mobileNumbel])) {
        return YES;
    }
    
    return NO;
}

//手机号码验证
- (BOOL) validateMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0-9])|(17[0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
//用户名
- (BOOL) validateUserName:(NSString *)name
{
    NSString *userNameRegex = @"[A-Za-z0-9_\\-\\u4e00-\\u9fa5]+";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}

//密码
//1、密码必须由数字、字符、特殊字符三种中的两种组成；
//2、密码长度不能少于6个字符不多于20；

- (BOOL) validatePassword:(NSString *)passWord
{
    NSString *passWordRegex = @"(?!^\\d+$)(?!^[a-zA-Z]+$)(?!^[_#@*.$]+$).{6,20}";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}

/**
 *  生成二维码
 */

- (UIImage *)createQRWithString:(NSString *)QRString
{
    //二维码滤镜
    CIFilter *filter=[CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    //恢复滤镜的默认属性
    [filter setDefaults];
    
    //将字符串转换成NSData
    NSData *data=[QRString dataUsingEncoding:NSUTF8StringEncoding];
    
    //通过KVO设置滤镜inputmessage数据
    [filter setValue:data forKey:@"inputMessage"];
    
    //获得滤镜输出的图像
    CIImage *outputImage=[filter outputImage];
    
    //将CIImage转换成UIImage,并放大显示
    return [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:100.0];
    
}

//改变二维码大小
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 创建bitmap;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 保存bitmap到图片
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
    
}


/**
 *  生成图片
 *
 *  @param color  图片颜色
 *  @param height 图片高度
 *
 *  @return 生成的图片
 */
- (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
   
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}
///**
// *  返回本机手机号
// *
// *  @return myNumber
// */
//- (NSString *)myNumber {
//    
//    return CTSettingCopyMyPhoneNumber();
//}

//农历转换函数
-(NSString *)LunarForSolar:(NSDate *)solarDate{
//    //天干名称
//    NSArray *cTianGan = [NSArray arrayWithObjects:@"甲",@"乙",@"丙",@"丁",@"戊",@"己",@"庚",@"辛",@"壬",@"癸", nil];
//    
//    //地支名称
//    NSArray *cDiZhi = [NSArray arrayWithObjects:@"子",@"丑",@"寅",@"卯",@"辰",@"巳",@"午",@"未",@"申",@"酉",@"戌",@"亥",nil];
//    
//    //属相名称
//    NSArray *cShuXiang = [NSArray arrayWithObjects:@"鼠",@"牛",@"虎",@"兔",@"龙",@"蛇",@"马",@"羊",@"猴",@"鸡",@"狗",@"猪",nil];
    
    //农历日期名
    NSArray *cDayName = [NSArray arrayWithObjects:@"*",@"初一",@"初二",@"初三",@"初四",@"初五",@"初六",@"初七",@"初八",@"初九",@"初十",
                         @"十一",@"十二",@"十三",@"十四",@"十五",@"十六",@"十七",@"十八",@"十九",@"二十",
                         @"廿一",@"廿二",@"廿三",@"廿四",@"廿五",@"廿六",@"廿七",@"廿八",@"廿九",@"三十",nil];
    
    //农历月份名
    NSArray *cMonName = [NSArray arrayWithObjects:@"*",@"正",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"十",@"十一",@"腊",nil];
    
    //公历每月前面的天数
    const int wMonthAdd[12] = {0,31,59,90,120,151,181,212,243,273,304,334};
    
    //农历数据
    const int wNongliData[100] = {2635,333387,1701,1748,267701,694,2391,133423,1175,396438
        ,3402,3749,331177,1453,694,201326,2350,465197,3221,3402
        ,400202,2901,1386,267611,605,2349,137515,2709,464533,1738
        ,2901,330421,1242,2651,199255,1323,529706,3733,1706,398762
        ,2741,1206,267438,2647,1318,204070,3477,461653,1386,2413
        ,330077,1197,2637,268877,3365,531109,2900,2922,398042,2395
        ,1179,267415,2635,661067,1701,1748,398772,2742,2391,330031
        ,1175,1611,200010,3749,527717,1452,2742,332397,2350,3222
        ,268949,3402,3493,133973,1386,464219,605,2349,334123,2709
        ,2890,267946,2773,592565,1210,2651,395863,1323,2707,265877};
    
    static NSInteger wCurYear,wCurMonth,wCurDay;
    static NSInteger nTheDate,nIsEnd,m,k,n,i,nBit;
    
    //取当前公历年、月、日
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:solarDate];
    wCurYear = [components year];
    wCurMonth = [components month];
    wCurDay = [components day];
    
    //计算到初始时间1921年2月8日的天数：1921-2-8(正月初一)
    nTheDate = (wCurYear - 1921) * 365 + (wCurYear - 1921) / 4 + wCurDay + wMonthAdd[wCurMonth - 1] - 38;
    if((!(wCurYear % 4)) && (wCurMonth > 2))
        nTheDate = nTheDate + 1;
    
    //计算农历天干、地支、月、日
    nIsEnd = 0;
    m = 0;
    while(nIsEnd != 1)
    {
        if(wNongliData[m] < 4095)
            k = 11;
        else
            k = 12;
        n = k;
        while(n>=0)
        {
            //获取wNongliData(m)的第n个二进制位的值
            nBit = wNongliData[m];
            for(i=1;i<n+1;i++)
                nBit = nBit/2;
            
            nBit = nBit % 2;
            
            if (nTheDate <= (29 + nBit))
            {
                nIsEnd = 1;
                break;
            }
            
            nTheDate = nTheDate - 29 - nBit;
            n = n - 1;
        }
        if(nIsEnd)
            break;
        m = m + 1;
    }
    wCurYear = 1921 + m;
    wCurMonth = k - n + 1;
    wCurDay = nTheDate;
    if (k == 12)
    {
        if (wCurMonth == wNongliData[m] / 65536 + 1)
            wCurMonth = 1 - wCurMonth;
        else if (wCurMonth > wNongliData[m] / 65536 + 1)
            wCurMonth = wCurMonth - 1;
    }
    
    //生成农历天干、地支、属相
//    NSString *szShuXiang = (NSString *)[cShuXiang objectAtIndex:((wCurYear - 4) % 60) % 12];
//    NSString *szNongli = [NSString stringWithFormat:@"%@(%@%@)年",szShuXiang, (NSString *)[cTianGan objectAtIndex:((wCurYear - 4) % 60) % 10],(NSString *)[cDiZhi objectAtIndex:((wCurYear - 4) % 60) % 12]];
    
    //生成农历月、日
    NSString *szNongliDay;
    if (wCurMonth < 1){
        szNongliDay = [NSString stringWithFormat:@"闰%@",(NSString *)[cMonName objectAtIndex:-1 * wCurMonth]];
    }
    else{
        szNongliDay = (NSString *)[cMonName objectAtIndex:wCurMonth];
    }
    
    NSString *lunarDate = [NSString stringWithFormat:@"%@月%@",szNongliDay,(NSString *)[cDayName objectAtIndex:wCurDay]];
    
    return lunarDate;
}
/**
 *  分割之后的字符串
 *  @param string 要分割的字符串
 *  @param stringStyle 分割标识
 *  @return array
 */
- (NSArray *)componentsSeparatedByString:(NSString *)string withComponentsSeparatedStyle:(NSString *)stringStyle {
    
    NSArray *stringArray = [string componentsSeparatedByString:stringStyle];
    return stringArray;
}




//判断网络
//- (NSInteger)statusOfInternetStatus
//{
//    Reachability * reach = [Reachability reachabilityForInternetConnection];
//   NSInteger status = [reach currentReachabilityStatus];
//    
//    switch (status) {
//        case NotReachable:{
//            return knowNo;
//        }
//            break;
//        case ReachableViaWiFi:{
//            
//            return isWifi    ;
//        }
//            break;
//        case ReachableViaWWAN:{
//            
//            return isWalan;
//        
//        }
//            break;
//        default:
//            return knowNo;
//            break;
//    }
//}

//- (BOOL)checkNetworkStatus{
//    Reachability * reach = [Reachability reachabilityForInternetConnection];
//    NSInteger status = [reach currentReachabilityStatus];
//    
//    BOOL isNetworkUse;
//    
//    switch (status) {
//        case NotReachable:{
//            isNetworkUse = NO;
//        }
//            break;
//        case ReachableViaWiFi:{
//            
//           isNetworkUse = YES;
//        }
//            break;
//        case ReachableViaWWAN:{
//            
//            isNetworkUse = YES;
//            
//        }
//             break;
//        default:
//            break;
//    }
//    return isNetworkUse;
//}


//UIImage转换为NSString
-(NSString*)imageToStringWithImage:(UIImage*)image
{
    //先将image转换为data类型,后面参数是品质
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    //再讲NSData转换为NSString
    NSString *string = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return string;
}

//将base64的字符串转换为图片
-(UIImage*)base64StringToImage:(NSString*)base64Str
{
    //将字符串转换为NSData
    NSData *imageData = [[NSData alloc]initWithBase64EncodedString:base64Str options:NSDataBase64DecodingIgnoreUnknownCharacters];
    //NSData到图片
    UIImage *image = [UIImage imageWithData:imageData];
    return image;
}

/**
 *  截取字符串
 *
 *  @param colorString 传入要截取的字符串
 *  @param index       位置
 *
 *  @return 截取之后
 */
- (NSString *)binzhouwColorString:(NSString *)colorString withIndex:(NSInteger)index {
    
    NSString *newStr = [colorString substringFromIndex:index];
    
    return newStr;
}


//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
/**
 *  照片旋转（大小超过2M会自动旋转）
 *
 *  @param aImage <#aImage description#>
 *
 *  @return <#return value description#>
 */
- (UIImage *)fixOrientationAction:(UIImage *)aImage {
    
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height, CGImageGetBitsPerComponent(aImage.CGImage), 0, CGImageGetColorSpace(aImage.CGImage), CGImageGetBitmapInfo(aImage.CGImage)); CGContextConcatCTM(ctx, transform); switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx); CGImageRelease(cgimg);
    return img;
    
}
/**
 *  去除html标签
 *
 *
 */
-(NSString *)filterHTML:(NSString *)html {
    
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    html = [html stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    return html;
}




//传入 秒  得到  xx：xx
-(NSString *)getMMSSFromSS:(NSInteger )totalTime{
    
    //format of time
    NSString *format_time;
    NSInteger hour =totalTime/3600;
    if (hour>0) {
        NSString * str_hour=[NSString stringWithFormat:@"%02ld",(long)hour];
        //format of minute
        NSString *str_minute = [NSString stringWithFormat:@"%02ld",(long)(totalTime-3600)/60];
        //format of second
        NSString *str_second = [NSString stringWithFormat:@"%02ld",(long)(totalTime-3600)%60];
        
        format_time= [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    }else{
        //format of minute
        NSString *str_minute = [NSString stringWithFormat:@"%02ld",(long)totalTime/60];
        //format of second
        NSString *str_second = [NSString stringWithFormat:@"%02ld",(long)totalTime%60];
        format_time= [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    }
    
    return format_time;
}



- (void)alertControllerWithViewController:(id) viewController Title:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *) cancelTitle sureButtonTitle:(NSString *) sureTitle cancelAction:(cancelActionBlock)cancelHandler sureAction:(sureActionBlock)sureHandler{

    CKAlertViewController * alertVC = [CKAlertViewController alertControllerWithTitle:title message:message];
    CKAlertAction *cancel = [CKAlertAction actionWithTitle:cancelTitle handler:^(CKAlertAction *action) {
        if (cancelHandler) {
            cancelHandler();
        }
    }];
    
    CKAlertAction *sure = [CKAlertAction actionWithTitle:sureTitle handler:^(CKAlertAction *action) {
        if (sureHandler) {
            sureHandler();
        }
    }];
    if (cancelTitle.length == 0) {
        [alertVC addAction:sure];
    }else{
        [alertVC addAction:cancel];
        [alertVC addAction:sure];
    }

    [viewController presentViewController:alertVC animated:NO completion:nil];
  
}
//url UTF-8转码
- (NSString *) stringByAddingUTF8String:(NSString *) url{
    
    NSString *encodedString = (NSString *)
    
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              
                                                              (CFStringRef)url,
                                                              
                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                              
                                                              NULL,
                                                              
                                                              kCFStringEncodingUTF8));
     return encodedString;
}
//判断一个字符串是否都是数字

- (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

//字符串转换为16进制数字
- (NSString *)convertStringToHexStr:(NSString *)str {
    if (!str || [str length] == 0) {
        return @"";
    }
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}

//字符串转换为BYTE[]
-(NSData*) hexToBytes:(NSString *)str{
    NSMutableData* data = [[NSMutableData alloc]init];
    int idx;
    for (idx = 0; idx+2 <= str.length; idx+=2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [str substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
    
}


-(NSString *)ToHex:(long long int)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    long long int ttmpig;
    long long int num = tmpid;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:nLetterValue=[[NSString alloc]initWithFormat:@"%lli",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
    }
    
    if (num<15) {
        str = [NSString stringWithFormat:@"0%@",str];
    }
    return str;
}




//// 缓存图片
//- (void) loadImageWithURL:(NSURL *) imageUrl completed:(JLJInternalCompletionBlock) completionedBlock{
//    [[SDWebImageManager sharedManager] loadImageWithURL:imageUrl options:SDWebImageRefreshCached progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
//        if (finished) {
//            completionedBlock(finished,imageUrl);
//        }
//    }];
//}
//- (void) removeImageForKey:(NSString *) key{
//    [[SDImageCache sharedImageCache] removeImageForKey:key withCompletion:nil];
//}
//// 取图片
//- (UIImage *) imageFromCacheForKey:(NSString *) key{
//    return [[SDImageCache sharedImageCache] imageFromCacheForKey:key];
//}

/**
 *  验证身份证号码
 *
 *  @param value 号码
 *
 *
 */
-(BOOL)validateIDCardNumber:(NSString *)value {
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSInteger length =0;
    if (!value) {
        return NO;
    }else {
        length = value.length;
        
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41",@"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    NSString *valueStart2 = [value substringToIndex:2];
    NSLog(@"%@",valueStart2);
    BOOL areaFlag =NO;
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return NO;
    }
    
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    
    int year =0;
    switch (length) {
        case 15:
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            
            
            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
        case 18:
            
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            
            
            if(numberofMatch >0) {
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                int Y = S %11;
                NSString *M =@"F";
                NSString *JYM =@"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else {
                    return NO;
                }
                
            }else {
                return NO;
            }
        default:
            return NO;
    }

    
}

- (void)bytesplit2byte:(Byte[])src orc:(Byte[])orc begin:(NSInteger)begin count:(NSInteger)count{
    

    memset(orc, 0, sizeof(char)*count);
    
    for (NSInteger i = begin; i < begin+count; i++){
        
        orc[i-begin] = src[i];
        
    }
    
}

- (NSInteger)numberWithHexString:(NSString *)hexString{
    
    const char *hexChar = [hexString cStringUsingEncoding:NSUTF8StringEncoding];
    int hexNumber; sscanf(hexChar, "%x", &hexNumber);
    return (NSInteger)hexNumber;

}

+ (NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
        
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        
        else
            
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr]; 
    } 
    return hexStr; 
} 

-(void)keepConnect{
    Byte byte[] = {0x41};
    NSData *data = [[NSData alloc]initWithBytes:byte length:1];
    send(self.socket, data.bytes, 1, 0);
        uint8_t buffer[100];        
        ssize_t recvLen = recv(kSocket, buffer, sizeof(buffer), 0);
        if (recvLen <=0) {
            [self creatSocket];
        }

}

-(void)creatSocket{
//    // socket
//    /**
//     参数
//     domain:    协议域，AF_INET（IPV4的网络开发）
//     type:      Socket 类型，SOCK_STREAM(TCP)/SOCK_DGRAM(UDP，报文)
//     protocol:  IPPROTO_TCP，协议，如果输入0，可以根据第二个参数，自动选择协议
//     
//     返回值
//     socket，如果 > 0 就表示成功
//     */
//   
    
    self.socket = socket(AF_INET, SOCK_STREAM, 0);
    
    if (self.socket > 0) {
        NSLog(@"Socket Create success %d", self.socket);
    } else {
        NSLog(@"Socket Create error");
    }
    
    //connection 连接到“服务器”
    /**
     参数
     1> 客户端socket
     2> 指向数据结构sockaddr的指针，其中包括目的端口和IP地址
     服务器的"结构体"地址，C语言没有对象
     3> 结构体数据长度
     返回值
     0 成功/其他 错误代号，非0即真
     */
    struct sockaddr_in serverAddress;
    // IPV4 - 协议
    serverAddress.sin_family = AF_INET;
    // inet_addr函数可以把ip地址转换成一个整数
    serverAddress.sin_addr.s_addr = inet_addr(ADDRESS.UTF8String);
    // 端口小端存储
    serverAddress.sin_port = htons(PORT);
    
     //
   int result =  connect(self.socket, (const struct sockaddr *)&serverAddress, sizeof(serverAddress));
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setInteger:self.socket forKey:@"socket"];
    
    dispatch_queue_t concurrentQueue = dispatch_queue_create("com.creat.concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(concurrentQueue, ^{
            self.timer= [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(checkSocket) userInfo:nil repeats:YES];
    });
    
  
 
    if (result < 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[JLJTools shareInstance]ShowErrorWithString:@"未成功连接服务器" withTime:0.5];
        });
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
//            [[JLJTools shareInstance]ShowWithString:@"连接服务器成功" withTime:0.5];
            NSLog(@"连接服务器成功");
        });

    }
    
    // 如果连接成功返回 YES
   // return (result == 0);

}

-(void)checkSocket{
    uint8_t buf[1];
    buf[0] = 0x41;
    send(kSocket, buf, 1, 0);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        uint8_t buffer[100];
        
        ssize_t recvLen = recv(kSocket, buffer, sizeof(buffer), 0);
        if (recvLen <=0) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [[JLJTools shareInstance]alertControllerWithViewController:self Title:nil message:@"已与服务器断开连接，是否重连" cancelButtonTitle:@"取消" sureButtonTitle:@"确定" cancelAction:^{
//                    
//                } sureAction:^{
//                        }];
                        [self creatSocket];
//            
//            });
 
        }else{
 
        }
    });
}

-(NSData *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    NSData *data = [mutStr dataUsingEncoding:NSUTF8StringEncoding];
    
    return data;
    
}

- (NSDictionary *)dictionaryWithJsonString:(uint8_t *)buffer lenth:(ssize_t)recvlen
{
    NSData *data = [NSData dataWithBytes:buffer length:recvlen];
    
    NSString *jsonString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
 
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
-(int)calcCrc16buf:(uint8_t[])buf offset:(int)offset len:(int)len
{
    char *data = (char*)buf;
    int ucCRCHi = (0xffff & 0xff00) >> 8;
    int ucCRCLo = 0xffff & 0x00ff;
    int iIndex;
    for (int i = 0; i < len; ++i) {
        iIndex = (ucCRCLo ^ data[offset + i]) & 0x00ff;
        ucCRCLo = ucCRCHi ^ auchCRCHi[iIndex];
        ucCRCHi = auchCRCLo[iIndex];
    }
    return ((ucCRCLo & 0x00ff) << 8) | ((ucCRCHi & 0x00ff) & 0xffff);
}



static char auchCRCHi[] = {
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
    0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,
    0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,
    0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,
    0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,
    0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,
    0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,
    0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,
    0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
    0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
    0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,
    0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,
    0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,
    0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,
    0x80,0x41,0x00,0xC1,0x81,0x40};

static char auchCRCLo[] = {
    0x00,0xC0,0xC1,0x01,0xC3,0x03,0x02,0xC2,0xC6,0x06,
    0x07,0xC7,0x05,0xC5,0xC4,0x04,0xCC,0x0C,0x0D,0xCD,
    0x0F,0xCF,0xCE,0x0E,0x0A,0xCA,0xCB,0x0B,0xC9,0x09,
    0x08,0xC8,0xD8,0x18,0x19,0xD9,0x1B,0xDB,0xDA,0x1A,
    0x1E,0xDE,0xDF,0x1F,0xDD,0x1D,0x1C,0xDC,0x14,0xD4,
    0xD5,0x15,0xD7,0x17,0x16,0xD6,0xD2,0x12,0x13,0xD3,
    0x11,0xD1,0xD0,0x10,0xF0,0x30,0x31,0xF1,0x33,0xF3,
    0xF2,0x32,0x36,0xF6,0xF7,0x37,0xF5,0x35,0x34,0xF4,
    0x3C,0xFC,0xFD,0x3D,0xFF,0x3F,0x3E,0xFE,0xFA,0x3A,
    0x3B,0xFB,0x39,0xF9,0xF8,0x38,0x28,0xE8,0xE9,0x29,
    0xEB,0x2B,0x2A,0xEA,0xEE,0x2E,0x2F,0xEF,0x2D,0xED,
    0xEC,0x2C,0xE4,0x24,0x25,0xE5,0x27,0xE7,0xE6,0x26,
    0x22,0xE2,0xE3,0x23,0xE1,0x21,0x20,0xE0,0xA0,0x60,
    0x61,0xA1,0x63,0xA3,0xA2,0x62,0x66,0xA6,0xA7,0x67,
    0xA5,0x65,0x64,0xA4,0x6C,0xAC,0xAD,0x6D,0xAF,0x6F,
    0x6E,0xAE,0xAA,0x6A,0x6B,0xAB,0x69,0xA9,0xA8,0x68,
    0x78,0xB8,0xB9,0x79,0xBB,0x7B,0x7A,0xBA,0xBE,0x7E,
    0x7F,0xBF,0x7D,0xBD,0xBC,0x7C,0xB4,0x74,0x75,0xB5,
    0x77,0xB7,0xB6,0x76,0x72,0xB2,0xB3,0x73,0xB1,0x71,
    0x70,0xB0,0x50,0x90,0x91,0x51,0x93,0x53,0x52,0x92,
    0x96,0x56,0x57,0x97,0x55,0x95,0x94,0x54,0x9C,0x5C,
    0x5D,0x9D,0x5F,0x9F,0x9E,0x5E,0x5A,0x9A,0x9B,0x5B,
    0x99,0x59,0x58,0x98,0x88,0x48,0x49,0x89,0x4B,0x8B,
    0x8A,0x4A,0x4E,0x8E,0x8F,0x4F,0x8D,0x4D,0x4C,0x8C,
    0x44,0x84,0x85,0x45,0x87,0x47,0x46,0x86,0x82,0x42,
    0x43,0x83,0x41,0x81,0x80,0x40};




@end
